package org.artifact.core.plugin.storage;

import java.util.Set;
import java.util.concurrent.Callable;

import org.artifact.core.db.BaseDao;
import org.artifact.core.lang.IPlugin;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
/**
 * 数据库落地插件
 * @author apple
 *
 */
public class StoragePlugin implements IPlugin {
	
	static final Log log = LogFactory.get(StoragePlugin.class);
	
	private Set<BaseDao<?>> daos;
	
	private Callable<Set<BaseDao<?>>> scanDao;
	private String crontab;
	public StoragePlugin(String crontab,Callable<Set<BaseDao<?>>> scanDao) {
		super();
		this.crontab = crontab;
		this.scanDao = scanDao;
	}

	public Callable<Set<BaseDao<?>>> getScanDao() {
		return scanDao;
	}

	public void setScanDao(Callable<Set<BaseDao<?>>> scanDao) {
		this.scanDao = scanDao;
	}

	@Override
	public boolean start() {
		try {
			daos = scanDao.call();
			// 检查表
			existsTable();
			
			CronUtil.schedule(crontab, new Task() {
			    @Override
			    public void execute() {
			    	finishAll();
			    }
			});

			// 支持秒级别定时任务
//			CronUtil.setMatchSecond(true);
			CronUtil.start();
			
			
			return true;
		} catch (Exception e) {
			log.error(e);
		}
		return false;
	}

	@Override
	public boolean stop() {
		// 停止定时
		CronUtil.stop();
		
		for (BaseDao<?> baseDao : daos) {
			baseDao.shutdown();
		}
		return true;
	}

	private void existsTable() {
		log.info("-> existsTable");
		for (BaseDao<?> baseDao : daos) {
			if (!baseDao.existsTable()) {
				baseDao.createTable();
			}
		}
	}
	
	
	public void finishAll() {
		log.info("-> finishAll");
		for (BaseDao<?> baseDao : daos) {
			baseDao.finishAll();
		}
	}
}
